package com.ty.cloudpicture.service.impl;
import java.io.IOException;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.ty.cloudpicture.api.aliyun.ALiYunAiApi;
import com.ty.cloudpicture.api.aliyun.model.CreateOutPaintingTaskRequest;
import com.ty.cloudpicture.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.ty.cloudpicture.common.ErrorCode;
import com.ty.cloudpicture.exception.BusinessException;
import com.ty.cloudpicture.exception.ThrowUtils;
import com.ty.cloudpicture.manager.CosManager;
import com.ty.cloudpicture.manager.upload.FilePictureUpload;
import com.ty.cloudpicture.manager.upload.PictureUploadTemplate;
import com.ty.cloudpicture.manager.upload.UrlPictureUpload;
import com.ty.cloudpicture.model.dto.file.UploadPictureResult;
import com.ty.cloudpicture.model.dto.picture.*;
import com.ty.cloudpicture.model.entity.Picture;
import com.ty.cloudpicture.model.entity.Space;
import com.ty.cloudpicture.model.entity.User;
import com.ty.cloudpicture.model.enums.PictureReviewStatusEnum;
import com.ty.cloudpicture.model.vo.PictureVO;
import com.ty.cloudpicture.model.vo.UserVO;
import com.ty.cloudpicture.service.PictureService;
import com.ty.cloudpicture.mapper.PictureMapper;
import com.ty.cloudpicture.service.SpaceService;
import com.ty.cloudpicture.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
* @author ong char
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-02-12 21:26:29
*/
@Service
@AllArgsConstructor
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{
    private final UserService userService;
    private final FilePictureUpload filePictureUpload;
    private final UrlPictureUpload urlPictureUpload;

    private final SpaceService spaceService;
    private final TransactionTemplate transactionTemplate;
    private final CosManager cosManager;
    private final ALiYunAiApi aliYunAiApi;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR, "未登录");
        ThrowUtils.throwIf(pictureUploadRequest==null, ErrorCode.PARAMS_ERROR);
        //判断空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "空间不存在");
            //校验额度
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间已满");
            }
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间存储照片数量已满");
            }
        }
        //检查是更新图片还是新增图片
        Long pictureId = null;
        if (pictureUploadRequest.getId() != null) {
            pictureId = pictureUploadRequest.getId();
        }
        //如果是更新图片，先判断图片是否存在
        Picture oldPicture;
        if (pictureId != null) {
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
            //仅本人和管理员可以更新图片信息
//            if (!userService.isAdmin(loginUser) && !loginUser.getId().equals(oldPicture.getUserId())){
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
//            checkPictureAuth(loginUser, oldPicture);
            //校验空间是否一致
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                if (ObjUtil.notEqual(oldPicture.getSpaceId(), spaceId)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间不一致");
                }
            }
        } else {
            oldPicture = null;
        }
        //上传图片，获取图片信息
        String uploadPathPrefix;
        if (spaceId == null) {
            //按照用户id划分目录
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        //区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        //构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setSpaceId(spaceId);
        String picName = pictureUploadRequest.getPicName();
        if (StrUtil.isBlank(picName) && StrUtil.isNotBlank(uploadPictureResult.getPicName())) {
            picName = uploadPictureResult.getPicName();
        }
        if (ObjUtil.isNotEmpty(oldPicture)){
            picture.setName(oldPicture.getName());
        }else {
            picture.setName(picName);
        }
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        this.fillReviewParams(picture, loginUser);
        //如果pictureId不为空，则表示更新，否则是新增
        if (pictureId != null) {
            //如果是更新，补充id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(LocalDateTime.now());
        }
        //开启事务，更新空间额度
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            //插入图片信息
            boolean save = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                //更新空间额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
//                        .setSql("totalSize=totalSize + "+picture.getPicSize())
//                        .setSql("totalCount=totalCount + 1")
                        .set(Space::getTotalSize, spaceService.getById(finalSpaceId).getTotalSize() + picture.getPicSize())
                        .set(Space::getTotalCount, spaceService.getById(finalSpaceId).getTotalCount() + 1)
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            }
            return picture;
        });
        //更新之后可以删除原先的照片
        if (oldPicture != null && picture.getSpaceId()!=null){
            this.clearPictureFile(oldPicture);
            transactionTemplate.execute(status -> {
                //更新空间额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
//                    .setSql("total_size=total_size+", oldPicture.getPicSize())
//                    .setSql("total_count=total_count+1")
                        .set(Space::getTotalSize, spaceService.getById(finalSpaceId).getTotalSize() - oldPicture.getPicSize())
                        .set(Space::getTotalCount, spaceService.getById(finalSpaceId).getTotalCount() - 1)
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
                return true;
            });
        }

//        ThrowUtils.throwIf(!save,ErrorCode.OPERATION_ERROR,"图片上传失败");
        //返回图片信息
        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
//        if(nullSpaceId){
//            queryWrapper.isNull("spaceId");
//        }else {
//            queryWrapper.eq(ObjUtil.isNotEmpty(spaceId),"spaceId",spaceId);
//        }
        if (StrUtil.isNotBlank(searchText)){
            queryWrapper.and(qw->qw.like("name",searchText)
                    .or().like("introduction",searchText));
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId),"spaceId",spaceId);
        queryWrapper.isNull(nullSpaceId,"spaceId");
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize),"picSize",picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth),"picWidth",picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight),"picHeight",picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale),"picScale",picScale);
        queryWrapper.like(StrUtil.isNotBlank(picFormat),"picFormat",picFormat);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId),"userId",userId);
        queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
        queryWrapper.like(StrUtil.isNotBlank(introduction),"introduction",introduction);
        queryWrapper.eq(StrUtil.isNotBlank(category),"category",category);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage),"reviewMessage",reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId),"reviewerId",reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus),"reviewStatus",reviewStatus);
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        //json数组查询
        if (CollUtil.isNotEmpty(tags)) {
            /* and (tag like "%\"Java\"%" and like "%\"Python\"%") */
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        //排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture) {
        if (picture == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片不存在");
        }
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        if (userId!=null && userId>0){
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)){
            return pictureVOPage;
        }
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        //获取用户id
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
        Map<Long, User> userIdUserMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        //填充用户信息
//        pictureVOList.forEach(pictureVO -> {
//            Long userId = pictureVO.getUserId();
//            User user=null;
//            if (userIdUserListMap.containsKey(userId)){
//                user=userIdUserListMap.get(userId).get(0);
//                pictureVO.setUser(userService.getUserVO(user));
//            }
//        });
        pictureVOList.forEach(pictureVO -> {
            Long userId=pictureVO.getUserId();
            User user=null;
            if (userIdUserMap.containsKey(userId)){
                user=userIdUserMap.get(userId);
                pictureVO.setUser(userService.getUserVO(user));
            }
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        if (ObjUtil.isNull(id) || ObjUtil.isNull(reviewStatus)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断是否存在
        Picture oldPicture = this.getById(id);
        if (oldPicture==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (reviewStatus==PictureReviewStatusEnum.REVIEWING.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复审核");
        }
        //状态修改
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest,picture);
        picture.setReviewTime(new Date());
        picture.setReviewerId(loginUser.getId());
        boolean updateResult = this.updateById(picture);
        ThrowUtils.throwIf(!updateResult,ErrorCode.OPERATION_ERROR);
    }
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public long uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //获取参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count>30,ErrorCode.PARAMS_ERROR,"最多上传30张图片");
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)){
            namePrefix = searchText;
        }
        //设置偏移量
        int offset = RandomUtil.randomInt(0, 100);
        //获取要抓取 的网站
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1&first=%d", searchText, offset);
        //连接网址获取信息
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取元素失败");
        }
        //获取dgControl类里的数据
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取元素失败");
        }
        //筛选img.ming元素
        Elements imgElementsList = div.select("img.mimg");
        int uploadCount = 0;
        //遍历元素
        for (Element element : imgElementsList) {
            String fileUrl = element.attr("src");
            if (StrUtil.isBlank(fileUrl)){
                log.info("当前链接为空，已跳过：{}", fileUrl);
                continue;
            }
            //处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex != -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            //上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (StrUtil.isNotBlank(namePrefix)){
                pictureUploadRequest.setPicName(namePrefix+(uploadCount+1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("上传成功：{}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.info("上传失败：{}", e);
                continue;
            }
            if (uploadCount >= count){
                break;
            }
        }
        //返回图片数量
        return uploadCount;
    }

//    @Override
//    public void checkPictureAuth(User loginUser, Picture picture) {
//        Long spaceId = picture.getSpaceId();
//        Long loginUserId = loginUser.getId();
//        Long PictureUserId = picture.getUserId();
//        if (PictureUserId == null){
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
//        }
//        if (spaceId == null) {
//            // 公共图库，仅本人或管理员可操作
//            if (!PictureUserId.equals(loginUserId) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
//        } else {
//            // 私有空间，仅空间管理员可操作
//            if (!PictureUserId.equals(loginUserId)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
//        }
//    }

    @Override
    public boolean deletePicture(Long id, User loginUser) {

        //判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //仅本人或者管理员可删除
//        checkPictureAuth(loginUser,oldPicture);
        // 校验权限
// 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(id);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        clearPictureFile(oldPicture);
        return true;
    }

    @Override
    public boolean editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest,picture);
        //将list转为String，利用JSONUtil.toJsonStr()方法
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //设置编辑时间
        picture.setEditTime(LocalDateTime.now());
        this.validPicture(picture);
        Long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        //仅本人或或管理员可编辑
//        this.checkPictureAuth(loginUser,oldPicture);
        this.fillReviewParams(oldPicture,loginUser);
        return this.updateById(picture);
    }
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断改图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        // 删除图片
        cosManager.deleteObject(pictureUrl);
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //参数校验
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String nameRule = pictureEditByBatchRequest.getNameRule();
        ThrowUtils.throwIf(spaceId ==null || CollectionUtils.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);;
        //空间权限校验
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        if (!Objects.equals(space.getUserId(), loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //查询指定图片，仅选择需要字段
        List<Picture> pictureList = this.lambdaQuery()
                .in(Picture::getId, pictureIdList)
                .eq(Picture::getSpaceId, spaceId)
                .select(Picture::getId,Picture::getSpaceId)
                .list();
        ThrowUtils.throwIf(CollectionUtils.isEmpty(pictureList), ErrorCode.NOT_FOUND_ERROR,"图片不存在");
//        fillPictureWithNameRule(pictureList, nameRule);
        int count=1;
        //更新分类和标签
        for (Picture picture : pictureList) {
            if (category != null) {
                picture.setCategory(category);
            }
            if (tags != null) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
            if (nameRule != null) {
                nameRule.replace("\\{序号}", String.valueOf(count++));
                picture.setName(nameRule);
            }
        }
        //更新图片
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量更新失败");
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        System.out.println("picture.getUrl() = " + picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }


    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
//    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
//        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
//            return;
//        }
//        long count = 1;
//        try {
//            for (Picture picture : pictureList) {
//                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
//                picture.setName(pictureName);
//            }
//        } catch (Exception e) {
//            log.error("名称解析错误", e);
//            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
//        }
//    }


}